package com.hitqz.robot.biz.controller;

import com.hitqz.robot.api.business.vo.BatteryLevelStatisticVo;
import com.hitqz.robot.biz.service.BatteryDataInfoService;
import com.hitqz.robot.common.core.util.R;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.MediaType;
import org.springframework.http.codec.ServerSentEvent;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import reactor.core.publisher.Flux;

import java.time.Duration;

/**
 * @author xupkun
 * @date 2024/12/17
 */
@RestController
@RequiredArgsConstructor
@RequestMapping("/statistic")
@Tag(name = "数据统计-flux方式")
@Slf4j
public class StatisticController {

    private final BatteryDataInfoService batteryDataInfoService;


    @GetMapping(value = "batteryLevel", produces = MediaType.TEXT_EVENT_STREAM_VALUE)
    @Operation(summary = "电池信息",description = "客户端可以采用EventSource进行连接")
    public Flux<ServerSentEvent<R<BatteryLevelStatisticVo>>> batteryLevel(
            @RequestParam(value = "statisticDate" ) String statisticDate,
            @RequestParam(value = "clientId" ) String clientId
    ) {
        Flux flux = Flux.interval(Duration.ofSeconds(1))
                .map(sequence -> ServerSentEvent.<R<BatteryLevelStatisticVo>>builder()
                        .id(String.valueOf(sequence))
                        .event("battery_level")
                        .data(R.ok(batteryDataInfoService.staticDate(clientId, statisticDate)))
                        .build());
        return flux;
    }


    @GetMapping(value = "battery")
    @Operation(summary = "电池信息")
    public R<BatteryLevelStatisticVo> battery(
            @RequestParam(value = "statisticDate" ) String statisticDate,
            @RequestParam(value = "clientId" ) String clientId
    ) {
        return R.ok(batteryDataInfoService.staticDate(clientId, statisticDate));
    }

}
